<template>
  <!-- 外部项目申报 流程 -->
  <div class="outside_index">
    <div class="left">
      <Top class="top_div" @topClickFn="topClickFn" />
      <div class="bottom" v-if="isShowNum == 1">
        <div class="bottom_info">
          <el-form
            :model="form"
            ref="formRef"
            label-width="120px"
            :rules="formRules"
          >
            <el-form-item
              label="项目名称"
              :prop="isCreateNew ? 'projectName' : ''"
            >
              <el-input
                v-model="form.projectName"
                placeholder="请输入..."
                :disabled="!isCreateNew"
              ></el-input>
            </el-form-item>

            <el-form-item
              label="主管单位"
              :prop="isCreateNew ? 'primaryUnit' : ''"
            >
              <el-input
                v-model="form.primaryUnit"
                :disabled="!isCreateNew"
                placeholder="请输入..."
              ></el-input>
            </el-form-item>

            <el-form-item label="合作单位">
              <el-input
                v-model="form.cooperateUnit"
                :disabled="!isCreateNew"
                placeholder="请输入..."
              ></el-input>
            </el-form-item>

            <el-form-item
              label="项目周期"
              :prop="isCreateNew ? 'projectCycle' : ''"
            >
              <el-date-picker
                style="width: 100%"
                v-model="form.projectCycle"
                :disabled="!isCreateNew"
                value-format="yyyy-MM-dd"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item
              label="立项申报书"
              :prop="isCreateNew ? 'appendixUrl' : ''"
              style="text-algin: left"
              class="upload_file"
            >
              <el-upload
                v-if="isCreateNew"
                :show-file-list="false"
                :action="uploadUrl"
                :on-success="handleSuccess"
                :headers="headers"
                :file-list="form.appendixUrl"
              >
                <el-button icon="el-icon-plus" size="small" type="primary">
                  添加附件
                </el-button>
              </el-upload>
              <div v-if="form.appendixUrl.length">
                <p
                  class="file_name"
                  v-for="(i, index) in form.appendixUrl"
                  :key="index"
                >
                  {{ i.fileName }}
                  <i
                    v-if="isCreateNew"
                    class="el-icon-circle-close"
                    @click="delFile(index)"
                  ></i>
                </p>
              </div>
            </el-form-item>
          </el-form>

          <div
            slot="footer"
            v-show="loginUser != '科研管理员' && isCreateNew"
            class="dialog-footer"
          >
            <el-button
              type="info"
              size="small"
              @click="submitData(0, 'formRef')"
            >
              取 消
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="submitData(1, 'formRef')"
            >
              暂 存
            </el-button>
            <el-button
              type="primary"
              size="small"
              @click="submitData(2, 'formRef')"
            >
              提 交
            </el-button>
          </div>
        </div>
      </div>
      <div v-if="isShowNum == 3"><Record /></div>
    </div>
    <div class="right">
      <Steps />
    </div>
  </div>
</template>

<script>
import moment from "moment";

import {
  apiProjectInfo,
  apiSubmitProject, // 申报提交
  apitempSave, // 暂存申报
  apiProjectProcess, // 17 查询项目流程
} from "@/api2/projectManagement/reporting";
import { uploadUrl } from "@/const";
import { getToken } from "@/utils/auth";

import Steps from "../components/steps.vue";
import Record from "./record.vue"; // 登记结果

import Top from "../components/top.vue";

export default {
  components: {
    Steps,
    Top,
    Record,
  },
  data() {
    const loginUser = JSON.parse(sessionStorage.getItem("loginUserinfo")).name;
    return {
      loginUser,
      projectId: null,
      isShowNum: 1, // 显示头部
      isDisadled: false,
      step_1: require("@/assets/static/imgs/step_1.png"),
      step_2: require("@/assets/static/imgs/step_2.png"),
      step_3: require("@/assets/static/imgs/step_3_2.png"),
      // processArr: [], //保存流程信息
      // params: {
      //   // 获取项目流程传递的参数
      //   projectCategory: this.$store.state.project.projectInfo.type,
      //   projectId: null,
      // },
      uploadUrl,
      headers: {
        Authorization: getToken(),
        platform: 'WEB'
      },
      // fileList: [],
      form: {
        appendixUrl: [], //上传的文件列表
      },
      // active: 0, //申报步骤
      // chooseItemType: {},
      // stepsArr: [
      //   {
      //     index: 0,
      //     text: "申报",
      //     isChoose: false,
      //     isLast: false,
      //   },
      //   {
      //     index: 1,
      //     text: "审核",
      //     isChoose: false,
      //     isLast: false,
      //   },
      //   {
      //     index: 0,
      //     text: "登记结果",
      //     isChoose: false,
      //     isLast: true,
      //   },
      // ],
      formRules: {
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        primaryUnit: [
          { required: true, message: "请输入主管单位", trigger: "blur" },
        ],
        // cooperateUnit: [
        //   { required: true, message: "请输入合作单位", trigger: "blur" },
        // ],
        projectCycle: [
          {
            required: true,
            message: "请选择日期",
            trigger: "change",
          },
        ],
        appendixUrl: [
          {
            required: true,
            message: "请上传立项申报书",
            trigger: "change",
          },
        ],
      },
    };
  },
  computed: {
    // // 是查看流程还是审批
    // isSeeProcess() {
    //   return this.$store.state.project.projectInfo.isSeeProcess;
    // },
    // 项目类型
    pType() {
      return this.$store.state.project.projectInfo.type;
    },

    // 是不是要创建新项目
    isCreateNew() {
      return this.$store.state.project.projectInfo.isCreateNew;
    },
  },
  created() {
    if (this.$route.params.id) {
      this.projectId = this.$route.params.id;
      this.isDisadled = true;
      this.getDateil();
    }
    this.getProjectProcess();
  },
  methods: {
    // 点击头部
    topClickFn(e) {
      this.isShowNum = e;
    },
    // 处理 待审批的数据
    async getDateil() {
      const res = await apiProjectInfo(this.projectId);
      if (res.code === 0) {
        const info = res.data;
        this.form = info;
        this.form.appendixUrl = JSON.parse(info.appendixUrl);

        // 将返回的时间"2023/04/14-2023/04/15" 转为['2023-04-14','2023-04-15']
        const dateString = info.projectCycle;
        const dateArray = dateString.split("-");
        this.form.projectCycle = dateArray.map((date) =>
          date.replace(/\//g, "-")
        );
      }
    },

    // 获取项目审核流程
    getProjectProcess() {
      const params = this.projectId
        ? { projectId: this.projectId }
        : { projectCategory: this.pType };

      apiProjectProcess(params).then((res) => {
        const processArr = res.code == 0 ? res.data : [];
        if (processArr.length) {
          for (let i = 0; i < processArr.length; i++) {
            switch (i) {
              case 0:
                processArr[i].imgSrc = this.step_1;
                break;
              case 1:
                processArr[i].imgSrc = this.step_2;
                break;
              case 2:
                processArr[i].imgSrc = this.step_3;
                break;
              case 3:
                processArr[i].imgSrc = this.step_4;
                break;
              default:
                processArr[i].imgSrc = this.step_5;
            }
          }
        }
        this.$store.commit("project/SET_PROCESSLIST", processArr);
      });
    },
    // 删除上传的文件
    delFile(index) {
      this.form.appendixUrl.splice(index, 1);
    },

    // 文件上传成功
    handleSuccess(res, file, fileList) {
      this.form.appendixUrl.push(res.data);
      this.$refs.formRef.validateField("appendixUrl"); // 手动触发fileList校验规则
    },

    // 取消
    reset() {
      this.form = {
        projectName: "",
        primaryUnit: "",
        cooperateUnit: "",
        projectCycle: [,],
        appendixUrl: [], //上传的文件列表
      };
    },

    submitData(subtype, name) {
      // subtype 0 取消 1 暂存 2 提交
      console.log(subtype);
      if (subtype == 0) {
        this.reset();
      } else {
        this.$refs[name].validate((valid) => {
          if (valid) {
            let url = this.form.appendixUrl.map((v) => {
              return {
                fileName: v.fileName,
                relativeFilePath: v.relativeFilePath,
                size: v.size,
                suffix: v.suffix,
                url: v.url,
              };
            });
            let data = {
              projectCategory: this.pType,
              appendixUrl: JSON.stringify(url),
              cooperateUnit: this.form.cooperateUnit,
              primaryUnit: this.form.primaryUnit,
              projectName: this.form.projectName,
              projectCycle:
                this.getFormatedTimeStr(this.form.projectCycle[0]) +
                "-" +
                this.getFormatedTimeStr(this.form.projectCycle[1]),
            };

            if (subtype == 2) {
              apiSubmitProject(data)
                .then((res) => {
                  if (res.code === 0) {
                    this.msgSuccess("提交成功");
                    this.reset();
                  } else {
                    this.msgError("提交失败");
                  }
                })
                .catch((err) => {
                  console.log(err);
                  this.msgError("提交失败");
                });
            } else {
              apitempSave(data)
                .then((res) => {
                  if (res.code === 0) {
                    this.msgSuccess("暂存成功");
                    this.reset();
                  } else {
                    this.msgError("暂存失败");
                  }
                })
                .catch((err) => {
                  console.log(err);
                  this.msgError("暂存失败");
                });
            }
          }
        });
      }
    },
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = "YYYY/MM/DD") {
      return moment(stamp).format(str);
    },
  },
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
  text-align: left;
}
::v-deep .el-input.is-disabled .el-input__inner,
::v-deep .el-range-editor.is-disabled input,
::v-deep .el-range-editor.is-disabled {
  background: #fff !important;
  color: #000;
}

.outside_index {
  background: #f4f5fc;

  margin: 0 auto;
  padding: 20px;
  display: flex;
  .left {
    flex: 17;
    margin-right: 15px;
    .top_div {
      width: 100% !important;
      background: #fff;
    }

    .bottom {
      width: 100%;
      height: 687px;
      background: #ffffff;
      box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
      .bottom_info {
        padding-top: 2rem;
        height: 100%;
        width: 922px;
        margin: 0 auto;
        position: relative;

        .dialog-footer {
          position: absolute;
          left: 50%;
          transform: translateX(-50%);
          bottom: 10px;
        }
      }
    }
  }
  .right {
    flex: 6;
    width: 390px;
    height: 747px;
    background: #ffffff;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.1);
    border-radius: 0px 0px 0px 0px;
    opacity: 1;
  }
}
.file_name {
  // height: 4.25rem;
  line-height: 0.5rem;
}
</style>
